package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"order/global"
	"order/models/mysql"
	"order/pkg"
	"path"
	"strconv"
	"time"
)

type OrderController struct {
	beego.Controller
}

// 图片上传并入库
func (o *OrderController) UploadByOrder() {
	user_id := o.Ctx.Input.GetData("userId").(string)
	userId, _ := strconv.Atoi(user_id)
	file, m, err := o.GetFile("img") //现场图片
	if err != nil {
		o.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "图片参数错误",
			Data: nil,
		}
		o.ServeJSON()
		return
	}
	types, _ := o.GetInt("types")     //报修分类
	comment := o.GetString("comment") //情况描述
	content := o.GetString("content") //联系信息
	if types == 0 || comment == "" || content == "" {
		o.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "参数不能为空",
			Data: nil,
		}
		o.ServeJSON()
		return
	}
	//判断图片格式
	ext := path.Ext(m.Filename)
	if ext != ".png" && ext != ".jpg" {
		o.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "上传图片格式错误,请上传后缀为.png或.jpg的文件",
			Data: nil,
		}
		o.ServeJSON()
		return
	}
	//判断图片是否小于10M
	if m.Size > 10*1024*1024 {
		o.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "上传图片过大,请上传小于10M的文件",
			Data: nil,
		}
		o.ServeJSON()
		return
	}
	filename := "upload/" + time.Now().Format("20060102150405") + ext
	upload := pkg.Upload(filename, file)
	var order = mysql.Order{
		UserId:  userId,
		Img:     upload,
		Types:   types,
		Comment: comment,
		Content: content,
		Status:  0,
	}
	db := order.CreateOrder()
	if db.RowsAffected != 1 || db.Error != nil {
		o.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "添加报修失败",
			Data: nil,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = global.JsonR{
		Code: 0,
		Msg:  "上传图片成功",
		Data: upload,
	}
	o.ServeJSON()
	return
}
